'use strict'
const fs = require('fs')
const archiver = require('archiver')
const homedir = __dirname
function timeString () {
  const dateData = new Date()
  const year = dateData.getFullYear()
  let month = dateData.getMonth() + 1
  let date = dateData.getDate()
  const hour = dateData.getHours()
  let minute = dateData.getMinutes()
  let second = dateData.getSeconds()
  month = (month < 10) ? '0' + month : month
  date = (date < 10) ? '0' + date : date
  minute = (minute < 10) ? '0' + minute : minute
  second = (second < 10) ? '0' + second : second
  return year + '' + month + '' + date + '' + hour + '' + minute + '' + second
}
let fileName = 'dist' + '-' + timeString() + '.zip'
// 配置要打包的路径列表,需要打包某些目录，添加到数组里面即可 相对路径
const target = ['dist']

// 默认在当前目录路径生成此文件 dist.zip
const zipFile = homedir + '\\' + fileName

// 检查文件是否存在于当前目录中。
fs.access(zipFile, fs.constants.F_OK, (err) => {
  console.log(`${zipFile} ${err ? '不存在' : '存在'}`)
  // if (err) fs.unlinkSync(zipFile)
})

const output = fs.createWriteStream(zipFile)
const archive = archiver('zip')

archive.on('error', function (err) {
  throw err
})

output.on('close', function () {
  console.log(`
     ----------------------------压缩完毕---------------------------
     生成文件大小${(archive.pointer() / 1024 / 1024).toFixed(1)}MB
     请在当前项目路径下寻找 dist.zip 文件,系统路径为 ${zipFile}
     ---------如需配置生成路径或文件名,请配置output---------
     `)
})

archive.pipe(output)
for (let i of target) {
  archive.directory(i, i)
}
archive.finalize()
